"""
交互式视频生成主程序
支持用户在关键步骤进行干预、编辑和优化
已优化：并行图像生成，大幅提升速度
"""

import argparse
from networkx import selfloop_edges
import yaml
import sys
import asyncio  # 新增：支持异步并行生成
from pathlib import Path

import platform
if platform.system() == 'Windows':
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    try:
        import nest_asyncio
        nest_asyncio.apply()
    except ImportError:
        pass
# 启用Windows终端颜色支持
import platform
if platform.system() == 'Windows':
    try:
        import ctypes
        kernel32 = ctypes.windll.kernel32
        kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
    except:
        pass

from mm_story_agent.interactive_agent import InteractiveAgent
from mm_story_agent import MMStoryAgent
from mm_story_agent.optimized_image_generator import OptimizedImageGenerator  # 新增：优化生成器


class InteractiveVideoGenerator:
    """交互式视频生成器"""
    
    def __init__(self, config: dict):
        self.config = config
        self.interactive = InteractiveAgent()
        self.agent = MMStoryAgent()
        
        # 提取关键配置
        self.story_dir = Path(config.get('story_dir', 'generated_stories/example'))
        self.story_dir.mkdir(parents=True, exist_ok=True)
 
    # def run(self):
    #     """执行交互式生成流程"""
    #     self.interactive.print_header("🎬 交互式视频生成系统")
        
    #     try:
    #         # 阶段1-4: 故事生成和编辑（保持不变）
    #         #pages = self.stage_1_generate_story()
    #         pages = self.enhanced_stage_1()
    #         if not pages:
    #             return
    #         pages = self.stage_2_edit_story(pages)
    #         prompts = self.stage_3_generate_prompts(pages)
    #         prompts = self.stage_4_edit_prompts(prompts, pages)
            
    #         # 🔥 新增：阶段4.5 - 生成数据可视化
    #         viz_paths = self.stage_4_5_generate_visualizations(pages)
            
    #         # 阶段5-8: 图像生成和视频合成（保持不变）
    #         image_paths = self.stage_5_generate_images(prompts, pages)
    #         image_paths = self.stage_6_regenerate_images(image_paths, prompts, pages)
            
    #         # 🔥 合并可视化图表到图像列表
    #         if viz_paths:
    #             image_paths = self.merge_visualizations(image_paths, viz_paths, pages)
            
    #         if not self.stage_7_final_confirmation(pages, image_paths):
    #             self.interactive.print_warning("用户取消了视频合成")
    #             return
            
    #         self.stage_8_compose_video(pages, image_paths)
    #         self.interactive.print_success("🎉 视频生成完成！")
            
    #     except KeyboardInterrupt:
    #         self.interactive.print_warning("\n⚠️  用户中断了操作")
    #         sys.exit(0)
    #     except Exception as e:
    #         self.interactive.print_error(f"发生错误: {e}")
    #         import traceback
    #         traceback.print_exc()
    #         sys.exit(1)
    def run(self):
        """执行交互式生成流程"""
        self.interactive.print_header("🎬 交互式视频生成系统")
        
        try:
            # 阶段1-8: 原有流程（保持不变）
            pages = self.enhanced_stage_1()
            if not pages:
                return
            pages = self.stage_2_edit_story(pages)
            prompts = self.stage_3_generate_prompts(pages)
            prompts = self.stage_4_edit_prompts(prompts, pages)
            viz_paths = self.stage_4_5_generate_visualizations(pages)
            image_paths = self.stage_5_generate_images(prompts, pages)
                # 🔥 新增: 阶段5.5 - 语音生成
            speech_generated = self.stage_5_5_generate_speech(pages)
            
            if not speech_generated:
                self.interactive.print_warning(
                    "未生成语音文件，视频将使用默认时长（每页5秒）"
                )
                if not self.interactive.get_yes_no("是否继续？", True):
                    return
            image_paths = self.stage_6_regenerate_images(image_paths, prompts, pages)
            
            if viz_paths:
                image_paths = self.merge_visualizations(image_paths, viz_paths, pages)
            
            if not self.stage_7_final_confirmation(pages, image_paths):
                self.interactive.print_warning("用户取消了视频合成")
                return
            
            self.stage_8_compose_video(pages, image_paths)
            
            # 🔥 新增：阶段9 - 生成交互式HTML
            self.stage_9_generate_interactive_html(pages, viz_paths)
            
            self.interactive.print_success("🎉 所有内容生成完成！")
            
        except KeyboardInterrupt:
            self.interactive.print_warning("\n⚠️  用户中断了操作")
            sys.exit(0)
        except Exception as e:
            self.interactive.print_error(f"发生错误: {e}")
            import traceback
            traceback.print_exc()
            sys.exit(1)

    def stage_4_5_generate_visualizations(self, pages: list) -> list:
        """阶段4.5: 生成数据可视化"""
        self.interactive.print_header("📊 阶段4.5: 数据可视化生成")
        
        # 检查是否启用
        viz_config = self.config.get('data_visualization', {})
        if not viz_config.get('enabled', False):
            self.interactive.print_info("数据可视化未启用，跳过此阶段")
            return []
        
        # 询问用户
        if not self.interactive.get_yes_no("是否生成数据可视化图表？", True):
            self.interactive.print_warning("跳过数据可视化")
            return []
        
        # 导入可视化模块
        from mm_story_agent.modality_agents.data_visualization_agent import DataVisualizationAgent
        
        # 创建可视化代理
        viz_agent = DataVisualizationAgent(
            output_dir=self.story_dir / "visualizations",
            style=viz_config.get('style', 'colorful')
        )
        
        # 生成可视化
        self.interactive.print_info("正在分析故事内容并生成图表...")
        viz_paths = viz_agent.generate_all_visualizations(
            pages,
            animated=viz_config.get('animated', True)
        )
        
        # 保存进度
        self.save_progress({
            'pages': pages,
            'visualizations': viz_paths
        })
        
        return viz_paths

    def stage_5_5_generate_speech(self, pages: list) -> bool:
        """
        阶段5.5: 生成语音（TTS）
        在图像生成后、视频合成前调用
        """
        self.interactive.print_header("🎙️ 阶段5.5: 生成语音")
        
        # 检查配置
        speech_config = self.config.get('speech_generation')
        if not speech_config:
            self.interactive.print_warning("未配置语音生成，将使用静音")
            return False
        
        # 检查语音目录
        speech_dir = self.story_dir / "speech"
        speech_dir.mkdir(parents=True, exist_ok=True)
        
        # 检查是否已有语音文件
        existing_speech = list(speech_dir.glob("p*.wav"))
        if existing_speech and len(existing_speech) >= len(pages):
            if self.interactive.get_yes_no(
                f"检测到 {len(existing_speech)} 个已存在的语音文件，是否跳过生成？", 
                True
            ):
                self.interactive.print_success("使用已存在的语音文件")
                return True
        
        # 询问是否生成语音
        if not self.interactive.get_yes_no("开始生成语音？", True):
            self.interactive.print_warning("跳过语音生成，视频将使用默认时长")
            return False
        
        # 显示配置信息
        params = speech_config.get('params', {})
        cfg = speech_config.get('cfg', {})
        
        print(f"\n当前配置:")
        print(f"  工具: {speech_config.get('tool')}")
        print(f"  采样率: {cfg.get('sample_rate', 16000)} Hz")
        print(f"  音色: {params.get('voice', 'longyuan')}")
        
        # 检查必要的密钥
        required_keys = ['access_key_id', 'access_key_secret', 'app_key']
        missing_keys = [k for k in required_keys if not params.get(k)]
        
        if missing_keys:
            self.interactive.print_error(f"缺少必要的密钥: {', '.join(missing_keys)}")
            self.interactive.print_warning("请在配置文件中设置或运行 setup_env.ps1")
            return False
        
        # 导入并创建语音生成代理
        try:
            from mm_story_agent.base import init_tool_instance
            speech_agent = init_tool_instance(speech_config)
            self.interactive.print_success("语音生成器初始化成功")
        except Exception as e:
            self.interactive.print_error(f"初始化语音生成器失败: {e}")
            return False
        
        # 准备参数
        speech_params = params.copy()
        speech_params['pages'] = pages
        speech_params['save_path'] = speech_dir
        
        # 生成语音
        self.interactive.print_info(f"正在为 {len(pages)} 个页面生成语音...")
        
        try:
            # 显示进度
            from tqdm import tqdm
            
            for i, page in enumerate(tqdm(pages, desc="生成语音"), 1):
                # 检查是否已存在
                speech_file = speech_dir / f"p{i}.wav"
                if speech_file.exists():
                    self.interactive.print_info(f"  页面 {i}: 已存在，跳过")
                    continue
                
                # 生成单个语音
                try:
                    # 调用语音生成
                    result = speech_agent.call_single(page, speech_dir, i)
                    
                    if result and Path(result).exists():
                        self.interactive.print_success(f"  页面 {i}: 成功")
                    else:
                        self.interactive.print_warning(f"  页面 {i}: 失败")
                    
                    # 避免请求过快
                    import time
                    time.sleep(0.5)
                    
                except Exception as e:
                    self.interactive.print_error(f"  页面 {i}: 错误 - {e}")
                    continue
            
            # 检查生成结果
            generated_files = list(speech_dir.glob("p*.wav"))
            success_count = len(generated_files)
            
            self.interactive.print_success(
                f"语音生成完成: {success_count}/{len(pages)} 个文件"
            )
            
            # 保存进度
            self.save_progress({
                'pages': pages,
                'speech_files': [str(f) for f in generated_files]
            })
            
            return success_count > 0
            
        except Exception as e:
            self.interactive.print_error(f"语音生成失败: {e}")
            import traceback
            traceback.print_exc()
            return False


    def stage_5_5_generate_speech_batch(self, pages: list) -> bool:
        """
        阶段5.5: 批量生成语音（使用原有的并行方法）
        这个版本调用 MMStoryAgent 的方法，支持并行生成
        """
        self.interactive.print_header("🎙️ 阶段5.5: 批量生成语音")
        
        # 检查配置
        speech_config = self.config.get('speech_generation')
        if not speech_config:
            self.interactive.print_warning("未配置语音生成")
            return False
        
        # 询问是否生成
        if not self.interactive.get_yes_no("开始批量生成语音？", True):
            self.interactive.print_warning("跳过语音生成")
            return False
        
        # 检查已存在的文件
        speech_dir = self.story_dir / "speech"
        speech_dir.mkdir(parents=True, exist_ok=True)
        existing = list(speech_dir.glob("p*.wav"))
        
        if existing:
            self.interactive.print_info(f"已存在 {len(existing)} 个语音文件")
            if self.interactive.get_yes_no("是否跳过已生成的？", True):
                if len(existing) >= len(pages):
                    return True
        
        try:
            # 使用 MMStoryAgent 的方法
            self.interactive.print_info("正在调用语音生成服务...")
            
            # 准备临时配置
            temp_config = {
                'speech_generation': speech_config,
                'story_dir': str(self.story_dir)
            }
            
            # 调用 MMStoryAgent 的语音生成
            from mm_story_agent.base import init_tool_instance
            speech_agent = init_tool_instance(speech_config)
            
            params = speech_config.get('params', {}).copy()
            params['pages'] = pages
            params['save_path'] = speech_dir
            
            # 执行生成
            result = speech_agent.call(params)
            
            # 检查结果
            generated = list(speech_dir.glob("p*.wav"))
            success = len(generated) > 0
            
            if success:
                self.interactive.print_success(
                    f"✅ 语音生成完成: {len(generated)}/{len(pages)} 个文件"
                )
            else:
                self.interactive.print_warning("⚠️ 没有生成语音文件")
            
            return success
            
        except Exception as e:
            self.interactive.print_error(f"语音生成失败: {e}")
            import traceback
            traceback.print_exc()
            return False


        def merge_visualizations(self, image_paths: list, viz_paths: list, 
                                pages: list) -> list:
            """合并可视化图表到图像列表"""
            self.interactive.print_header("🔀 合并可视化图表")
            
            if not viz_paths:
                return image_paths
            
            # 策略1: 在特定位置插入
            merged = image_paths.copy()
            
            # 在每3页后插入一个可视化
            insert_interval = max(1, len(pages) // len(viz_paths))
            
            for i, viz_path in enumerate(viz_paths):
                insert_pos = min((i + 1) * insert_interval, len(merged))
                merged.insert(insert_pos, viz_path)
                self.interactive.print_success(f"✅ 在位置 {insert_pos} 插入图表")
            
            self.interactive.print_info(f"合并后共 {len(merged)} 张图片（含 {len(viz_paths)} 张图表）")
            
            return merged
        def stage_1_generate_story(self) -> list:
            """阶段1: 生成故事内容"""
            self.interactive.print_header("📖 阶段1: 生成故事内容")
            
            # 检查是否有已保存的会话
            session = self.interactive.load_session(self.story_dir)
            if session and 'pages' in session:
                if self.interactive.get_yes_no("检测到之前的会话，是否继续？", True):
                    self.interactive.print_success(f"已加载 {len(session['pages'])} 页故事")
                    return session['pages']
            
            # 显示配置信息
            story_config = self.config.get('story_writer', {})
            params = story_config.get('params', {})
            input_type = params.get('input_type', 'topic')
            
            print(f"\n当前配置:")
            print(f"  模式: {input_type}")
            if input_type == 'long_text':
                long_text = params.get('long_text', '')
                print(f"  文本预览: {long_text[:100]}...")
            else:
                print(f"  主题: {params.get('story_topic', 'N/A')}")
            
            target_pages = params.get('target_pages', 8)
            print(f"  目标页数: {target_pages}")
            
            # 确认是否开始生成
            if not self.interactive.get_yes_no("\n开始生成故事？", True):
                return []
            
            # 调用故事生成
            self.interactive.print_info("正在生成故事...")
            
            # 这里使用原有的story_writer
            from mm_story_agent.base import init_tool_instance
            story_writer = init_tool_instance(story_config)
            pages = story_writer.call(params)
            
            self.interactive.print_success(f"故事生成完成！共 {len(pages)} 页")
            
            # 保存中间结果
            self.save_progress({'pages': pages})
            
            return pages
        
        def stage_2_edit_story(self, pages: list) -> list:
            """阶段2: 编辑故事内容"""
            self.interactive.print_header("✏️  阶段2: 编辑故事内容")
            
            # 使用交互式编辑
            edited_pages = self.interactive.review_and_edit_pages(pages)
            
            # 保存编辑结果
            self.save_progress({'pages': edited_pages})
            
            return edited_pages
        
        def stage_3_generate_prompts(self, pages: list) -> list:
            """阶段3: 生成图像提示词"""
            self.interactive.print_header("🎨 阶段3: 生成图像提示词")
            
            self.interactive.print_info("正在为每个页面生成图像提示词...")
            
            # 使用image_agent的提示词生成功能
            from mm_story_agent.base import init_tool_instance
            image_config = self.config.get('image_generation', {})
            
            # 创建临时的image agent来生成提示词
            image_agent = init_tool_instance(image_config)
            
            # 提取角色
            role_dict = image_agent.extract_role_from_story(pages)
            self.interactive.print_success(f"识别到 {len(role_dict)} 个角色")
            
            # 生成提示词
            prompts = image_agent.generate_image_prompt_from_story(pages)
            
            # 添加角色描述
            prompts_with_roles = []
            for prompt in prompts:
                for role, role_desc in role_dict.items():
                    if role in prompt:
                        prompt = prompt.replace(role, role_desc)
                prompts_with_roles.append(prompt)
            
            self.interactive.print_success(f"生成了 {len(prompts_with_roles)} 个提示词")
            
            # 保存
            self.save_progress({
                'pages': pages,
                'prompts': prompts_with_roles,
                'roles': role_dict
            })
            
            return prompts_with_roles
        
        def stage_4_edit_prompts(self, prompts: list, pages: list) -> list:
            """阶段4: 优化提示词"""
            self.interactive.print_header("✨ 阶段4: 优化提示词")
            
            # 交互式编辑提示词
            edited_prompts = self.interactive.review_and_edit_prompts(prompts, pages)
            
            # 保存
            self.save_progress({
                'pages': pages,
                'prompts': edited_prompts
            })
            
            return edited_prompts
        
        def stage_5_generate_images(self, prompts: list, pages: list) -> list:
            """阶段5: 生成图像（优化版 - 并行生成）"""
            self.interactive.print_header("🖼️ 阶段5: 生成图像（并行模式）")
            
            self.interactive.print_info(f"准备并行生成 {len(prompts)} 张图片...")
            
            if not self.interactive.get_yes_no("开始生成图像？（使用并行加速）", True):
                self.interactive.print_warning("跳过图像生成")
                return []
            
            # 获取配置
            image_config = self.config.get('image_generation', {})
            params = image_config.get('params', {})
            
            # 优先从环境变量读取 API key
            import os
            api_key = params.get('api_key') or os.getenv('DASHSCOPE_API_KEY')
            
            if not api_key:
                self.interactive.print_error("未配置 api_key")
                self.interactive.print_warning("请在配置文件中设置 api_key 或运行 setup_env.ps1")
                return []
            
            # 准备路径
            image_dir = self.story_dir / "image"
            cache_dir = self.story_dir / ".cache"
            
            # 优化提示词
            from mm_story_agent.base import init_tool_instance
            image_agent = init_tool_instance(image_config)
            style_name = params.get('style_name', 'Storybook')
            
            optimized_prompts = []
            for prompt in prompts:
                opt_prompt = image_agent.optimize_prompt(prompt, style_name)
                optimized_prompts.append(opt_prompt)
            
            # 创建优化生成器
            generator = OptimizedImageGenerator(
                api_key=api_key,
                max_concurrent=params.get('max_concurrent', 4),
                request_interval=params.get('request_interval', 1.0),
                cache_dir=cache_dir if params.get('enable_cache', True) else None,
                max_retries=params.get('max_retries', 3)
            )
            try:
                # 检查是否有运行中的事件循环
                loop = asyncio.get_event_loop()
                if loop.is_running():
                    # 如果有运行中的循环，创建新的循环
                    import nest_asyncio
                    nest_asyncio.apply()
            except RuntimeError:
                pass
            # 并行生成
            self.interactive.print_info("⚡ 使用并行模式生成中...")
            images = asyncio.run(
                generator.generate_batch(optimized_prompts, image_dir)
            )
            
            # 保存进度
            self.save_progress({
                'pages': pages,
                'prompts': prompts,
                'images': images
            })
            
            # 统计成功率
            success_count = sum(1 for img in images if img is not None)
            self.interactive.print_success(
                f"图像生成完成！成功 {success_count}/{len(images)} 张"
            )
            
            return images
        
        def stage_6_regenerate_images(self, image_paths: list, prompts: list, pages: list) -> list:
            """阶段6: 检查并重新生成图像"""
            self.interactive.print_header("🔄 阶段6: 图像检查与重新生成")

            # 🔥 添加检查：如果没有图像，直接返回
            if not image_paths or all(img is None for img in image_paths):
                self.interactive.print_error("没有成功生成的图像，无法进入重新生成阶段")
                self.interactive.print_warning("请检查:")
                self.interactive.print_warning("  1. API key 是否正确配置")
                self.interactive.print_warning("  2. 网络连接是否正常")
                self.interactive.print_warning("  3. API 额度是否充足")
                
                if self.interactive.get_yes_no("是否重新尝试生成所有图像？", True):
                    return self.stage_5_generate_images(prompts, pages)
                else:
                    return image_paths
            
            # 让用户选择需要重新生成的图像
            regenerate_indices = self.interactive.review_images_and_select_regenerate(
                image_paths, pages
            )
            
            if not regenerate_indices:
                self.interactive.print_success("无需重新生成图像")
                return image_paths
            
            # 重新生成选定的图像
            self.interactive.print_info(f"开始重新生成 {len(regenerate_indices)} 张图片...")
            
            from mm_story_agent.base import init_tool_instance
            image_config = self.config.get('image_generation', {})
            image_agent = init_tool_instance(image_config)
            
            image_dir = self.story_dir / "image"
            style_name = image_config.get('params', {}).get('style_name', 'Storybook')
            
            new_image_paths = image_paths.copy()
            
            for idx in regenerate_indices:
                try:
                    self.interactive.print_info(f"重新生成第 {idx + 1} 张图片...")
                    
                    # 询问是否修改提示词
                    if self.interactive.get_yes_no(f"是否修改第 {idx + 1} 张图片的提示词？", False):
                        print(f"原提示词: {prompts[idx]}")
                        new_prompt = self.interactive.get_input("新提示词", prompts[idx])
                        prompts[idx] = new_prompt
                    
                    # 重新生成
                    image_path = image_agent.call_dashscope_api_with_wait(
                        prompt=image_agent.optimize_prompt(prompts[idx], style_name),
                        save_path=image_dir,
                        index=idx + 1
                    )
                    new_image_paths[idx] = image_path
                    self.interactive.print_success(f"✅ 第 {idx + 1} 张图片重新生成成功")
                    
                    # 等待
                    import time
                    time.sleep(image_agent.request_interval)
                    
                except Exception as e:
                    self.interactive.print_error(f"第 {idx + 1} 张图片重新生成失败: {e}")
            
            # 保存
            self.save_progress({
                'pages': pages,
                'prompts': prompts,
                'images': new_image_paths
            })
            
            return new_image_paths
        
        def stage_7_final_confirmation(self, pages: list, image_paths: list) -> bool:
            """阶段7: 最终确认"""
            self.interactive.print_header("✅ 阶段7: 最终确认")
            
            return self.interactive.final_confirmation(pages, image_paths)
        
    

        def stage_8_compose_video(self, pages: list, image_paths: list):
            """阶段8: 合成视频"""
            self.interactive.print_header("🎬 阶段8: 合成视频")
            
            self.interactive.print_info("正在合成视频...")
            
            # 调用视频合成
            video_config = self.config.get('video_compose', {})
            
            if not video_config:
                self.interactive.print_warning("未配置视频合成，跳过")
                return
            
            from mm_story_agent.base import init_tool_instance
            video_agent = init_tool_instance(video_config)
            
            # 准备参数
            params = video_config.get('params', {}).copy()
            params['pages'] = pages
            params['story_dir'] = str(self.story_dir)
            
            # 🔥 关键修复：传入图片路径列表
            if image_paths:
                # 转换为字符串路径（如果是 Path 对象）
                image_paths_str = [str(p) if p else None for p in image_paths]
                # 过滤掉 None 值
                image_paths_str = [p for p in image_paths_str if p is not None]
                params['image_paths'] = image_paths_str
                
                self.interactive.print_info(f"使用 {len(image_paths_str)} 个图片文件")
                for idx, path in enumerate(image_paths_str, start=1):
                    from pathlib import Path
                    self.interactive.print_info(f"  {idx}. {Path(path).name}")
            else:
                self.interactive.print_warning("未提供图片路径，将尝试自动查找")
            
            # 执行合成
            video_agent.call(params)
            
            output_path = self.story_dir / "output.mp4"
            self.interactive.print_success(f"视频已保存: {output_path}")
            
        def save_progress(self, data: dict):
            """保存进度"""
            self.interactive.save_session(data, self.story_dir)

            # 阶段9: 生成交互式 HTML 版本
        # def stage_9_generate_html(self, pages: list, visualizations: list):
        #     from mm_story_agent.modality_agents.interactive_narrative_agent import InteractiveNarrativeAgent
            
        #     html_agent = InteractiveNarrativeAgent(
        #         output_dir=self.story_dir,
        #         theme="fantasy"
        #     )
            
        #     html_path = html_agent.generate_interactive_story(
        #         pages=pages,
        #         title="我的互动故事",
        #         visualizations=visualizations
        #     )
            
        #     print(f"✅ HTML 版本已生成: {html_path}")

        def stage_9_generate_interactive_html(self, pages: list, viz_paths: list = None):
            """阶段9: 生成交互式HTML"""
            self.interactive.print_header("🌐 阶段9: 生成交互式HTML")
            
            # 询问用户
            if not self.interactive.get_yes_no("是否生成交互式HTML版本？", True):
                self.interactive.print_warning("跳过HTML生成")
                return
            
            # 导入交互式叙事代理
            from mm_story_agent.modality_agents.interactive_narrative_agent import InteractiveNarrativeAgent
            
            # 获取故事标题
            story_config = self.config.get('story_writer', {})
            params = story_config.get('params', {})
            title = params.get('story_topic', '我的故事')
            
            # 选择主题
            theme_choice = self.interactive.get_choice(
                "选择HTML主题",
                ["默认", "暗黑", "奇幻", "科幻"],
                0
            )
            theme_map = {0: 'default', 1: 'dark', 2: 'fantasy', 3: 'scifi'}
            theme = theme_map[theme_choice]
            
            # 创建代理
            html_agent = InteractiveNarrativeAgent(
                output_dir=self.story_dir.parent / "interactive_stories",
                theme=theme
            )
            
            # 准备可视化数据
            visualizations = None
            if viz_paths:
                # 从可视化路径提取数据
                from mm_story_agent.modality_agents.data_visualization_agent import DataVisualizationAgent
                viz_agent = DataVisualizationAgent(
                    output_dir=self.story_dir / "visualizations",
                    style='colorful'
                )
                visualizations = viz_agent.extract_data_from_story(pages)
                if not visualizations:
                    visualizations = viz_agent._create_demo_visualizations(len(pages))
            
            # 生成HTML
            self.interactive.print_info("正在生成交互式HTML...")
            html_path = html_agent.generate_interactive_story(
                pages=pages,
                title=title,
                visualizations=visualizations
            )
            
            self.interactive.print_success(f"✅ HTML已生成: {html_path}")
            
            # 询问是否在浏览器中打开
            if self.interactive.get_yes_no("是否在浏览器中打开？", True):
                import webbrowser
                webbrowser.open(f"file://{Path(html_path).absolute()}")
                
        def enhanced_stage_1(self):
            """增强的阶段1"""
            # 选择生成模式
            mode = self.interactive.get_choice(
                "选择生成模式",
                ["一次性生成", "逐段生成", "取消"],
                1
            )
            
            if mode == 1:
                return self.incremental_generation()
            else:
                return self.stage_1_generate_story()
            
            # def incremental_generation(self) -> list:
            #     """逐段生成故事"""
            #     self.interactive.print_section("逐段生成模式")
                
            #     story_config = self.config.get('story_writer', {})
            #     params = story_config.get('params', {})
            #     target_pages = int(self.interactive.get_input("目标页数", str(params.get('target_pages', 8))))
                
            #     pages = []
                
            #     for i in range(target_pages):
            #         self.interactive.print_info(f"\n正在生成第 {i+1}/{target_pages} 页...")
                    
            #         # 调用原有的生成功能（这里简化）
            #         # 实际使用时需要修改 story_writer 支持单页生成
            #         from mm_story_agent.base import init_tool_instance
            #         story_writer = init_tool_instance(story_config)
                    
            #         # 临时方案：生成完整故事后取当前页
            #         # 你需要根据实际情况修改这部分
            #         if not pages:
            #             all_pages = story_writer.call(params)
            #             if i < len(all_pages):
            #                 new_page = all_pages[i]
            #             else:
            #                 new_page = f"第 {i+1} 页内容"
            #         else:
            #             new_page = f"基于前文生成的第 {i+1} 页"
                    
            #         # 显示生成结果
            #         # print(f"\n{self.interactive.Colors.CYAN}生成内容:{self.interactive.Colors.END}")
            #         # print(new_page)
            #         self.interactive.print_info("生成内容:")
            #         print(new_page)
                    
            #         # 用户选择
            #         action = self.interactive.get_choice(
            #             "\n对这一页满意吗？",
            #             ["✅ 满意，继续", "🔄 重新生成", "✏️  手动编辑", "❌ 停止生成"],
            #             0
            #         )
                    
            #         if action == 0:
            #             pages.append(new_page)
            #         elif action == 1:
            #             # 重新生成（简化：直接添加）
            #             pages.append(new_page)
            #         elif action == 2:
            #             # edited = input(f"{self.interactive.Colors.CYAN}请输入修改后的内容: {self.interactive.Colors.END}").strip()
            #             edited = self.interactive.get_input("请输入修改后的内容", new_page).strip()
            #             pages.append(edited if edited else new_page)
            #         else:
            #             break
                
            #     self.save_progress({'pages': pages})
            #     return pages
        def incremental_generation(self) -> list:
            """逐段生成故事"""
            self.interactive.print_section("逐段生成模式")
            
            story_config = self.config.get('story_writer', {})
            params = story_config.get('params', {})
            target_pages = int(self.interactive.get_input("目标页数", str(params.get('target_pages', 8))))
            
            # 先生成完整故事
            from mm_story_agent.base import init_tool_instance
            story_writer = init_tool_instance(story_config)
            
            self.interactive.print_info("正在生成完整故事...")
            all_pages = story_writer.call(params)
            
            if len(all_pages) < target_pages:
                self.interactive.print_warning(f"只生成了 {len(all_pages)} 页，少于目标 {target_pages} 页")
                target_pages = len(all_pages)
            
            pages = []
            
            # 逐页展示并让用户确认/编辑
            for i in range(target_pages):
                self.interactive.print_info(f"\n正在展示第 {i+1}/{target_pages} 页...")
                
                new_page = all_pages[i] if i < len(all_pages) else f"第 {i+1} 页内容"
                
                # 显示生成结果
                self.interactive.print_info("生成内容:")
                print(new_page)
                
                # 用户选择
                action = self.interactive.get_choice(
                    "\n对这一页满意吗？",
                    ["✅ 满意,继续", "🔄 重新生成此页", "✏️ 手动编辑", "❌ 停止生成"],
                    0
                )
                
                if action == 0:  # 满意
                    pages.append(new_page)
                elif action == 1:  # 重新生成
                    self.interactive.print_info("重新生成当前页...")
                    # 重新调用生成（这里简化处理，实际可以调用单页生成）
                    regenerated = story_writer.call(params)
                    if i < len(regenerated):
                        pages.append(regenerated[i])
                    else:
                        pages.append(new_page)
                elif action == 2:  # 手动编辑
                    edited = self.interactive.get_input("请输入修改后的内容", new_page).strip()
                    pages.append(edited if edited else new_page)
                else:  # 停止
                    break
            
            self.save_progress({'pages': pages})
            return pages

def main():
    parser = argparse.ArgumentParser(
        description='交互式视频生成系统 - 支持对话式生成和内容优化'
    )
    parser.add_argument("--config", "-c", type=str, required=True,
                       help="配置文件路径")
    parser.add_argument("--auto", action="store_true",
                       help="自动模式（跳过所有交互）")
    
    args = parser.parse_args()
    
    # 加载配置
    config_path = Path(args.config)
    if not config_path.exists():
        print(f"❌ 配置文件不存在: {args.config}")
        sys.exit(1)
    
    with open(config_path, 'r', encoding='utf-8') as f:
        config = yaml.load(f, Loader=yaml.FullLoader)
    
    # 运行交互式生成器
    generator = InteractiveVideoGenerator(config)
    generator.run()

   


if __name__ == "__main__":
    main()